package com.wf.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.constant.RedisConstant;
import com.wf.domain.User;
import com.wf.domain.UserRole;
import com.wf.dto.LoginDTO;
import com.wf.dto.UserDTO;
import com.wf.exception.ApartmentException;
import com.wf.mapper.UserMapper;
import com.wf.mapper.UserRoleMapper;
import com.wf.service.UserService;
import com.wf.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author mpk16
 * @description 针对表【user(用户信息表)】的数据库操作Service实现
 * @createDate 2024-08-03 13:39:49
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RedisUtil redisUtil;

    @Override
    @Transactional
    public User login(LoginDTO loginDTO) {
        User user = null;
        String identifier = Validator.isMobile(loginDTO.getPhone()) ? loginDTO.getPhone() : loginDTO.getEmail();
        boolean isMobile = Validator.isMobile(loginDTO.getPhone());

        if (isMobile || Validator.isEmail(loginDTO.getEmail())) {
            user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(isMobile ? User::getPhone : User::getEmail, identifier));

            if (ObjectUtil.isEmpty(user)) {
                user = new User();
                user.setPhone(isMobile ? loginDTO.getPhone() : null);
                user.setEmail(isMobile ? null : loginDTO.getEmail());
                user.setNickname(isMobile ? "手机用户" : "邮箱用户");
                user.setSex("保密");
                user.setLastLoginTime(LocalDateTime.now());
                user.setUsername(identifier);
                userMapper.insert(user);
                // 设置用户角色为普通用户
                userRoleMapper.insert(new UserRole(user.getUserId(),2L));
            } else {
                user.setLastLoginTime(LocalDateTime.now());
                userMapper.updateById(user);
            }
        }

        return user;
    }



    @Override
    @Transactional
    public User loginByWx(String openid) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, openid));
        if (user == null) {
            user = new User();
            user.setUsername(openid);
            user.setNickname("微信用户");
            //默认性别2：未知
            user.setSex("保密");
            user.setAvatar("https://wfyn.oss-cn-hangzhou.aliyuncs.com/wxavatar.jpg");
            userMapper.insert(user);
            // 设置用户角色为普通用户
            UserRole role = new UserRole();
            role.setRoleId(2L);
            role.setUseId(user.getUserId());
            userRoleMapper.insert(role);
        } else {
            user.setLastLoginTime(LocalDateTime.now());
        }
        userMapper.updateById(user);
        return user;
    }

    @Override
    public List<UserDTO> selectUser(String username, Integer roleId) {
        return userMapper.selectUser(username, roleId);
    }


    @Override
    @Transactional
    public boolean updatePhoneOrEmail(User user) throws ApartmentException {
        if (Validator.isEmail(user.getEmail())) {
            String code = (String) redisUtil.get(RedisConstant.APARTMENT_USER_INFO_BY_EMAIL_CODE + user.getEmail());
            if (StrUtil.equals(code, user.getCode())) {
                user.setEmail(user.getEmail());
                try {
                    return this.updateById(user);
                } catch (Exception e) {
                    throw new ApartmentException("该邮箱已绑定用户！");
                }
            }

        } else if (Validator.isMobile(user.getPhone())) {
            String code = (String) redisUtil.get(RedisConstant.APARTMENT_USER_INFO_BY_PHONE_CODE + user.getPhone());
            if (StrUtil.equals(code, user.getCode())) {
                user.setPhone(user.getPhone());
                try {
                    return this.updateById(user);
                } catch (Exception e) {
                    throw new ApartmentException("该手机号已绑定用户！");
                }


            }
        } else {
            return false;
        }
        return false;
    }
}




